<template>
  <div
    v-loading="loading"
    class="tree-graph">
    <RelationGraph
      :key="`treeGraph${showType}`"
      ref="seeksRelationGraph"
      class="relation-graph"
      :options="graphOptions"
      :on-node-click="onNodeClick">
      <span slot="node" slot-scope="{node}" :title="node.text">{{ node.text }}</span>
    </RelationGraph>
  </div>
</template>

<script>
import { crmCustomerReadAPI } from '@/api/crm/customer'

import RelationGraph from '@/components/RelationGraph'

import { objDeepCopy } from '@/utils'

export default {
  // TreeGraph
  name: 'TreeGraph',

  components: {
    RelationGraph
  },

  props: {
    showType: [String, Number], // 1  2
    id: [String, Number],
    graphData: Object
  },

  data() {
    return {
      loading: false,
      detailDetail: {}
    }
  },

  computed: {
    graphOptions() {
      if (this.showType === 1) {
        return {
          layouts: [
            {
              from: 'left',
              layoutName: 'tree',
              defaultJunctionPoint: 'lr',
              defaultNodeShape: 0,
              defaultLineShape: 4,
              min_per_width: 300,
              max_per_width: 800,
              centerOffset_x: -100
            }
          ],
          defaultLineShape: 4,
          defaultJunctionPoint: 'lr',
          defaultNodeShape: 1,
          defaultNodeWidth: '120',
          // defaultNodeHeight: '50',
          defaultNodeBorderWidth: 0
        }
      }
      return {
        layouts: [
          {
            from: 'top',
            layoutName: 'tree',
            defaultJunctionPoint: 'tb',
            defaultNodeShape: 0,
            defaultLineShape: 4,
            min_per_width: 200,
            max_per_width: 600,
            min_per_height: 150
            // max_per_height: '50'
          }
        ],
        defaultLineShape: 4, // 默认的线条样式（1:直线/2:样式2/3:样式3/4:折线/5:样式5/6:样式6）
        defaultJunctionPoint: 'tb', // 	默认的连线与节点接触的方式（border:边缘/ltrb:上下左右/tb:上下/lr:左右）当布局为树状布局时应使用tb或者lr，这样才会好看
        defaultNodeShape: 1, // 默认的节点形状，0:圆形；1:矩形
        defaultNodeWidth: '120', // 默认的节点宽度
        // defaultNodeHeight: '50', // 默认的节点高度
        defaultNodeBorderWidth: 0 // 	默认的节点边框粗细（像素）
      }
    }
  },

  watch: {
    graphData: {
      handler(val) {
        this.$nextTick(() => {
          if (!val || !val.rootId) return
          this.getCustomerDetail(objDeepCopy(val)) // 该组件内部有操作，复制避免影响外部数据
        })
      },
      immediate: true
    },

    showType: {
      handler(val) {
        this.$nextTick(() => {
          if (val === 1 || val === 2) {
            if (!this.graphData || !this.graphData.rootId) return
            this.getCustomerDetail(this.graphData)
          }
        })
      }
    }
  },

  methods: {
    /**
     * @description: 客户详情
     * @return {*}
     */
    getCustomerDetail(valData) {
      if (this.detailDetail?.customerId === this.id) {
        this.setGraphData(this.detailDetail, valData)
      } else {
        this.loading = true
        crmCustomerReadAPI({
          customerId: this.id
        })
          .then(res => {
            this.loading = false
            const resData = res.data || {}
            this.detailDetail = resData
            this.setGraphData(resData, valData)
          })
          .catch(() => {
            this.loading = false
          })
      }
    },

    setGraphData(resData, valData) {
      const copyData = objDeepCopy(valData)
      copyData.nodes = copyData.nodes.filter(item => {
        return (this.showType === 1 && [1, 2].includes(item.data?.type)) ||
        (this.showType === 2 && [3, 4].includes(item.data?.type))
      })

      const getValidNodeIds = (nodes, id, result) => {
        // 获取与当前id 相关连的节点
        const validNodes = nodes.filter(node => node.data?.targetCustomerId === id || node.data?.sourceCustomerId === id)
        validNodes.forEach(validNode => {
          if (validNode && !result.includes(validNode.id)) {
            result.push(validNode.id)
            const children = [validNode.data?.targetCustomerId, validNode.data?.sourceCustomerId]
            children.forEach(childId => {
              if (childId !== validNode.id) {
                getValidNodeIds(nodes, childId, result)
              }
            })
          }
        })
      }

      const validNodeIds = []
      // 获取有效连贯的IDs
      getValidNodeIds(copyData.nodes, this.id, validNodeIds)

      // 过滤nodes
      copyData.nodes = copyData.nodes.filter(item => {
        return validNodeIds.includes(item.id)
      })

      copyData.links = copyData.links.filter(item => {
        return ((this.showType === 1 && [1, 2].includes(item.data?.type)) ||
        (this.showType === 2 && [3, 4].includes(item.data?.type))) && (
          validNodeIds.includes(item.data?.targetCustomerId) && validNodeIds.includes(item.data?.sourceCustomerId)
        )
      })

      const jsonData = copyData.nodes.length === 0 ? {
        rootId: this.id,
        nodes: [{
          id: resData.customerId,
          text: resData.customerName,
          color: '#f59a23',
          data: resData
        }],
        links: []
      } : copyData
      console.log('jsonData---', jsonData)
      this.$refs.seeksRelationGraph.setJsonData(objDeepCopy(jsonData), () => {
        this.$nextTick(() => {
          this.$refs.seeksRelationGraph.zoom(-20)
        })
      })
    },

    /**
     * @description: 获取有效展示名称
     * @param {*} name
     * @return {*}
     */
    getShowNodeName(name, length = 10) {
      // if (name && name.length > length) {
      //   return name.slice(0, length) + '...'
      // }
      return name
    },

    /**
     * 节点点击
     */
    onNodeClick(nodeObject, $event) {
      console.log('onNodeClick:', nodeObject)
      if (nodeObject.data?.relationsId) {
        this.$emit('detail', nodeObject.id)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .c-node-text {
    cursor: pointer;
  }
}

::v-deep .relation-graph {
  .rel-node {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    > span {
      display: flex;
      /* stylelint-disable-next-line value-no-vendor-prefix */
      display: -webkit-box;
      max-height: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
    }
  }
}
</style>
